package com.incar.chuxing.activity.personal;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.activity.WebViewActivity;
import com.incar.chuxing.activity.WebViewNewUserActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.DrawerEvent;
import com.incar.chuxing.bean.LoginBean;
import com.incar.chuxing.bean.SmsCodeBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.CheckRegexUtils;
import com.incar.chuxing.utils.DensityUtils;
import com.incar.chuxing.utils.Dialogs.LoginStatusDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_phoneNum)
    EditText loginPhoneNum;
    @BindView(R.id.login_getSms)
    TextView loginGetSms;
    @BindView(R.id.login_smsCode)
    EditText loginSmsCode;
    @BindView(R.id.login_protocol)
    TextView loginProtocol;
    @BindView(R.id.login_confirm)
    TextView loginConfirm;
    @BindView(R.id.progress_bar_login)
    RelativeLayout progressBarLogin;

    @BindView(R.id.layout_content)
    RelativeLayout layout_content;
    @BindView(R.id.layout_scrollView)
    ScrollView layout_scrollView;
    @BindView(R.id.iv_log)
    ImageView iv_log;
    @BindView(R.id.layout_agreement)
    LinearLayout layoutAgreement;


    private int screenHeight = 0;//屏幕高度
    private int keyHeight = 0; //软件盘弹起后所占高度
    private float scale = 0.6f; //logo缩放比例

    private PushAgent mPushAgent;
    private String phoneNum;
    private String smsCode;
    private Context mContext = this;
    private int seconds = 60;
    public LocationClient mLocationClient = null;
    public MyLocationListener mListener = new MyLocationListener();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (seconds > 0) {
                        loginGetSms.setClickable(false);
                        loginGetSms.setText(seconds-- + "s");
                        //每过1000毫秒发送消息
                        handler.sendEmptyMessageDelayed(0, 1000);

                    } else {
                        seconds = 60;
                        loginGetSms.setClickable(true);
                        loginGetSms.setText("获取验证码");
                        checkPhoneNum();

                    }
                    break;
            }
        }
    };

    @Override
    public int getLayoutId() {

        return R.layout.activity_login;
    }


    @Override
    public void initData() {
        if (BuildConfig.DEBUG) {
            findViewById(R.id.debug_entry).setVisibility(View.VISIBLE);
        }
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        try {
            mPushAgent.deleteAlias(((MyApplication) getApplication()).getUid(), "USER", new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean b, String s) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        SPUtils.getInstance(mContext).clearSharePreference();
        ((MyApplication) getApplication()).setUid(null);
        ((MyApplication) getApplication()).setToken(null);
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {
            File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
            if (fileDir != null && fileDir.listFiles() != null) {
                File[] files = fileDir.listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg")) {
                        files[i].delete();
                    }
                }
            }
        }

        //声明LocationClient类
        mLocationClient = new LocationClient(mContext);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        mLocationClient.setLocOption(option);

        //注册监听函数
        mLocationClient.registerLocationListener(mListener);

        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        keyHeight = screenHeight / 5;//弹起高度为屏幕高度的1/5
        showLogAnim();

        loginPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                checkPhoneNum();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        loginSmsCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(loginSmsCode.getText().toString()) && loginSmsCode.getText().length() == 4 && !TextUtils.isEmpty(loginPhoneNum.getText().toString())) {
                    //61 368
                    //48 290
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) loginConfirm.getLayoutParams();
                    layoutParams.width = DensityUtils.dp2px(mContext, 302);
                    layoutParams.height = DensityUtils.dp2px(mContext, 61);
                    layoutParams.addRule(Gravity.CENTER_HORIZONTAL);
                    layoutParams.setMargins(0, DensityUtils.dp2px(mContext, 54), 0, 0);
                    loginConfirm.setLayoutParams(layoutParams);
                    loginConfirm.setBackground(getResources().getDrawable(R.drawable.button_login_blue));
                    loginConfirm.setClickable(true);

                } else {

                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) loginConfirm.getLayoutParams();
                    layoutParams.width = DensityUtils.dp2px(mContext, 290);
                    layoutParams.height = DensityUtils.dp2px(mContext, 48);
                    layoutParams.addRule(Gravity.CENTER_HORIZONTAL);
                    layoutParams.setMargins(0, DensityUtils.dp2px(mContext, 60), 0, 0);
                    loginConfirm.setLayoutParams(layoutParams);
                    loginConfirm.setBackgroundResource(R.drawable.btn_gray_bg);
                    loginConfirm.setClickable(false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    @Override
    public void initView() {
        loginGetSms.setClickable(false);
        loginConfirm.setClickable(false);
    }

    @OnClick({R.id.login_getSms, R.id.login_protocol, R.id.login_confirm, R.id.debug_entry})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_getSms:
                phoneNum = loginPhoneNum.getText().toString() + "";
                if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                    loginGetSms.setClickable(false);
                    sendSms(phoneNum);
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.inputPhoneNum), ToastUtils.LENGTH_SHORT).show();
                }
                break;
            case R.id.login_protocol:
                Intent intent = new Intent();
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "用户协议");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_user_agreement));
                startActivity(intent);
                break;
            case R.id.login_confirm:
                showLoadingDialog("正在登录...");
                startLocation();
                break;
            case R.id.debug_entry:
                Intent intent1 = new Intent();
                intent1.setClass(mContext, DebugModeActivity.class);
                startActivity(intent1);
                break;
        }
    }

    private void sendSms(String phoneNum) {
        showLoadingDialog("正在发送...");


        try {
            Map<String, String> requestFieldMap = ((MyApplication) getApplication()).getRequestFieldMap();
            Type typeParseMapOne = new TypeToken<Map<String, String>>() {
            }.getType();
            JSONObject bodyJson = new JSONObject(new Gson().toJson(requestFieldMap, typeParseMapOne));
            bodyJson.put("phoneNum", phoneNum);
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());


            ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).sendSms(body).enqueue(new Callback<SmsCodeBean>() {
                @Override
                public void onResponse(Call<SmsCodeBean> call, Response<SmsCodeBean> response) {
                    dismissLoadingDialog();
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            ToastUtils.makeText(mContext, "验证码发送中", ToastUtils.LENGTH_SHORT).show();
                            //重发验证码倒计时
                            loginGetSms.setTextColor(getResources().getColor(R.color.black2));
                            handler.sendEmptyMessage(0);
                        } else {
                            loginGetSms.setClickable(true);
                            ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                        }
                    } else {
                        loginGetSms.setClickable(true);
                        ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<SmsCodeBean> call, Throwable t) {
                    dismissLoadingDialog();
                    loginGetSms.setClickable(true);
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    Logger.d("neterror", "004" + t.toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startLocation() {
        mLocationClient.start();
    }

    private void login(String phoneNum, String sms) {
        try {
            Map<String, String> requestFieldMap = ((MyApplication) getApplication()).getRequestFieldMap();
            Type typeParseMapOne = new TypeToken<Map<String, String>>() {
            }.getType();
            JSONObject bodyJson = new JSONObject(new Gson().toJson(requestFieldMap, typeParseMapOne));
            bodyJson.put("phoneNum", phoneNum);
            bodyJson.put("code", sms);
            bodyJson.put("deviceToken", SPUtils.getInstance(mContext).getStringValue(SPKey.DEVICE_TOKEN));
            bodyJson.put("channel_from", "mydadao");
            bodyJson.put("channel_product", "android");
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
            ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).login(body).enqueue(new Callback<LoginBean>() {
                @Override
                public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            //  showLoginStatusDialog(response.body().getMessage(),R.drawable.login_success_icon);
                            try {
                                mPushAgent.deleteAlias(((MyApplication) getApplication()).getUid(), "USER", new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean b, String s) {

                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            LoginBean.AttachmentBean.UserModelBean userModel = response.body().getAttachment().getUserModel();
                            ((MyApplication) getApplication()).setUid(userModel.getId());
                            ((MyApplication) getApplication()).setHeaderToken(response.body().getAttachment().getXincartoken());
                            ((MyApplication) getApplication()).setToken(userModel.getToken());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_PHONE_NUM, userModel.getPhoneNum());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_NICK, userModel.getName());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_STATUS, userModel.getStatus() + "");
                            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_PICTURE, userModel.getPicture() + "");
                            SPUtils.getInstance(mContext).removeValue(SPKey.USER_PIC_LOCAL_PATH);

                            SPUtils.getInstance(mContext).putStringValue(SPKey.OPEN_ID, userModel.getOpenid());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getUserModel().getIdentityStatus() + "");
                            SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getUserModel().getLicenseStatus() + "");
                            SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_TIME, 0);
                            EventBus.getDefault().post(new DrawerEvent(true));//通知抽屉可以打开否！
                            try {
                                mPushAgent.addAlias(((MyApplication) getApplication()).getUid(), "USER", new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean b, String s) {

                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (response.body().getAttachment().getUserModel().getIsNewUser() == 0) {
                                Intent intent = new Intent(mContext, MainActivity.class);
                                intent.putExtra("jumpCode", 1);
                                startActivity(intent);
                            } else {
                                Intent intent_guide = new Intent();
                                Logger.i("printTokenMap", ((MyApplication) getApplication()).getCookieMap().toString());
                                intent_guide.setClass(mContext, WebViewNewUserActivity.class);
                                intent_guide.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "");
                                intent_guide.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_new_user_welcome));
                                startActivity(intent_guide);
                            }
                            AppManager.getAppManager().finishActivity();
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, response.body().getMessage(), 1, ToastUtils.LENGTH_SHORT).show();
                            //   showLoginStatusDialog( response.body().getMessage(),R.drawable.login_success_icon);
                        }
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<LoginBean> call, Throwable t) {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    Logger.d("neterror", "005");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //定位结果监听
    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            mLocationClient.stop();

            if (!BuildConfig.DEBUG) {
                ((MyApplication) getApplication()).setAreaCode(location != null ? location.getCityCode() : "131");
                ((MyApplication) getApplication()).setAdCode(location != null ? location.getAdCode() : "110105");
                DecimalFormat df = new DecimalFormat("#.0000000");
                ((MyApplication) getApplication()).setCurPosition(location != null ? df.format(location.getLatitude()) : "", location != null ? df.format(location.getLongitude()) : "");
                SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, location != null ? location.getCity() : "");
            } else {
                switch (SPUtils.getInstance(mContext).getIntValue("$s_locationMode")) {
                    case 0:
                    case 1:
                        ((MyApplication) getApplication()).setAreaCode(location != null ? location.getCityCode() : "131");
                        ((MyApplication) getApplication()).setAdCode(location != null ? location.getAdCode() : "110105");
                        DecimalFormat df = new DecimalFormat("#.0000000");
                        ((MyApplication) getApplication()).setCurPosition(location != null ? df.format(location.getLatitude()) : "", location != null ? df.format(location.getLongitude()) : "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, location != null ? location.getCity() : "");

                        break;
                    case 2:
                        ((MyApplication) getApplication()).setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                        ((MyApplication) getApplication()).setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                        ((MyApplication) getApplication()).setCurPosition(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude"),
                                SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude"));
                        break;
                }

            }

            smsCode = loginSmsCode.getText().toString();
            phoneNum = loginPhoneNum.getText().toString();
            if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                if (!smsCode.equals("") && smsCode.length() == 4) {
                    login(phoneNum, smsCode);
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, "请输入验证码", 1, ToastUtils.LENGTH_SHORT).show();
                }
            } else {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.inputPhoneNum), 1, ToastUtils.LENGTH_SHORT).show();
            }
        }
    }


    /* @Override
     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
         if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
             if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                 showLoadingDialog("正在登录...");
                 mLocationClient.start();
             } else if (grantResults.length == 1) {
                 dismissLoadingDialog();
                 final DialogTwoButton inCarDialog = new DialogTwoButton(LoginActivity.this);

                 inCarDialog.setMessage("您已拒绝定位权限");
                 inCarDialog.setCheckDefaultListener("确定", new DialogTwoButton.OnCheckResultListener() {
                     @Override
                     public void onYesClick() {
                         inCarDialog.dismiss();
                         startLocation();
                     }
                 });
                 inCarDialog.setCheckNoListener("取消", new DialogTwoButton.OnCheckNoListener() {
                     @Override
                     public void onNoClick() {
                         inCarDialog.dismiss();
                     }
                 });
                 inCarDialog.setCancelable(false);
                 inCarDialog.show();
             } else {
                 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
             }
         }
     }
 */
    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        super.onDestroy();
    }

    //弹框
    private void showLoginStatusDialog(String message, int view) {
        final LoginStatusDialog loginStatusDialog = new LoginStatusDialog(mContext);
        loginStatusDialog.setMessage(message);
        loginStatusDialog.setImageView(R.drawable.login_fail_icon);
        loginStatusDialog.show();
        //处理接收到的消息的方法
        new Handler(arg0 -> {
            loginStatusDialog.dismiss();
            return false;
        }).sendEmptyMessageDelayed(0, 3000); //表示延时三秒进行任务的执行
    }

    private void checkPhoneNum() {
        if (CheckRegexUtils.checkPhoneNum(loginPhoneNum.getText().toString()) && loginGetSms.getText().toString().equals("获取验证码")) {
            loginGetSms.setTextColor(getResources().getColor(R.color.login_getCode));
            loginGetSms.setClickable(true);
        } else {
            loginGetSms.setTextColor(getResources().getColor(R.color.black2));
            loginGetSms.setClickable(false);
        }
    }

    private void showLogAnim() {
        /**
         * 禁止键盘弹起的时候可以滚动
         */
        layout_scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        layout_scrollView.addOnLayoutChangeListener(new ViewGroup.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
              /* old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值
              现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起*/
                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                    int dist = (layout_content.getBottom() - bottom) / 3;
                    if (dist > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(layout_content, "translationY", 0.0f, -dist);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        zoomIn(iv_log, dist);
                    }

                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                    if ((layout_content.getBottom() - oldBottom) > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(layout_content, "translationY", layout_content.getTranslationY(), 0);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        //键盘收回后，logo恢复原来大小，位置同样回到初始位置
                        zoomOut(iv_log);
                    }
                }
            }
        });
    }

    /**
     * 缩小
     *
     * @param view
     */
    public void zoomIn(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    /**
     * 放大
     *
     * @param view
     */
    public void zoomOut(final View view) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        try {
            startActivity(intent);
        } catch (Exception ignored) {
            AppManager.getAppManager().AppExit(mContext);
        }
    }
}
